package com.leetcode.www;

/**
 * Creared with IntelliJ IDEA.
 * Description:给你一个整数数组 nums，将 nums 中的的所有偶数元素移动到数组的前面，后跟所有奇数元素。
 *
 * 返回满足此条件的 任一数组 作为答案
 * User:yxd
 * Date:2022-04-28
 * Time:21:56
 */
public class Everyday905 {
    public int[] sortArrayByParity2(int[] nums) {//额外数组加双指针
        int n = nums.length;
        int[] res = new int[n];
        int left = 0, right = n - 1;
        for (int num : nums) {
            if (num % 2 == 0) {
                res[left++] = num;
            } else {
                res[right--] = num;
            }
        }
        return res;
    }
    public int[] sortArrayByParity1(int[] nums) {//两次遍历
        int n = nums.length, index = 0;
        int[] res = new int[n];
        for (int num : nums) {
            if (num % 2 == 0) {
                res[index++] = num;
            }
        }
        for (int num : nums) {
            if (num % 2 == 1) {
                res[index++] = num;
            }
        }
        return res;
    }

    public int[] sortArrayByParity(int[] nums) {//双指针,原地交换
        if(nums.length == 1){
            return nums;
        }
        int l = 0;
        int r = nums.length - 1;
        while(l < r){
            while(l < r && nums[l] % 2 == 0){
                l ++;
            }
            while(l < r && nums[r] % 2 == 1){
                r --;
            }
            int a = nums[l];
            nums[l] = nums[r];
            nums[r] = a;
        }
        return nums;
    }
}
